<template>
  <div class="script-audit-container">
    <div class="header">
      <h2>剧本审核</h2>
      <el-button @click="getScriptList" :icon="RefreshRight">刷新</el-button>
    </div>

    <!-- 剧本列表 -->
    <el-table
      :data="scriptList"
      border
      style="width: 100%"
      v-loading="loading"
      empty-text="暂无待审核剧本"
    >
      <el-table-column prop="id" label="ID" width="80" />

      <el-table-column label="封面" width="100">
        <template #default="{ row }">
          <el-image
            :src="`${BASE_IMAGE_URL}/${row.contentFile}`"
            fit="cover"
            style="width: 60px; height: 84px; border-radius: 4px"
            :preview-src-list="[`${BASE_IMAGE_URL}/${row.contentFile}`]"
            preview-teleported
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>

      <el-table-column prop="title" label="剧本名称" min-width="150" />

      <el-table-column prop="author" label="作者" width="120" />

      <el-table-column prop="publishName" label="出版社" width="150" />

      <el-table-column prop="categoryId" label="分类" width="100">
        <template #default="{ row }">
          {{ getCategoryName(row.categoryId) }}
        </template>
      </el-table-column>

      <el-table-column prop="price" label="价格" width="100">
        <template #default="{ row }">
          ¥{{ row.price }}
        </template>
      </el-table-column>

      <el-table-column prop="usageDays" label="使用天数" width="100">
        <template #default="{ row }">
          {{ row.usageDays }} 天
        </template>
      </el-table-column>

      <el-table-column prop="publishDate" label="发布日期" width="120" />

      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            size="small"
            @click="handleViewDetail(row)"
          >
            查看详情
          </el-button>
          <el-button
            link
            type="success"
            size="small"
            @click="handleAudit(row, 1)"
            :disabled="row.status !== 0"
          >
            通过
          </el-button>
          <el-button
            link
            type="danger"
            size="small"
            @click="handleAudit(row, 2)"
            :disabled="row.status !== 0"
          >
            拒绝
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 剧本详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="剧本详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="script-detail">
        <div v-if="currentScript" class="detail-content">
          <!-- 剧本封面和基本信息 -->
          <div class="detail-header">
            <div class="detail-cover">
              <el-image
                :src="`${BASE_IMAGE_URL}/${currentScript.contentFile}`"
                :alt="currentScript.title"
                fit="cover"
              >
                <template #error>
                  <div class="image-error-large">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="detail-basic-info">
              <h2 class="detail-title">{{ currentScript.title }}</h2>
              <div class="info-item">
                <span class="info-label">作者：</span>
                <span class="info-value">{{ currentScript.author }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">出版社：</span>
                <span class="info-value">{{ currentScript.publishName }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">出版日期：</span>
                <span class="info-value">{{ currentScript.publishDate }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">分类：</span>
                <span class="info-value">{{ getCategoryName(currentScript.categoryId) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">使用天数：</span>
                <span class="info-value">{{ currentScript.usageDays }} 天</span>
              </div>
              <div class="info-item price-item">
                <span class="info-label">价格：</span>
                <span class="price-value">¥{{ currentScript.price }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">状态：</span>
                <el-tag :type="getStatusType(currentScript.status)">
                  {{ getStatusText(currentScript.status) }}
                </el-tag>
              </div>
            </div>
          </div>

          <!-- 剧本简介 -->
          <div class="detail-description">
            <h3 class="section-title">剧本简介</h3>
            <p class="description-text">{{ currentScript.description || '暂无简介' }}</p>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button
          v-if="currentScript?.status === 0"
          type="success"
          @click="handleAudit(currentScript, 1)"
        >
          通过审核
        </el-button>
        <el-button
          v-if="currentScript?.status === 0"
          type="danger"
          @click="handleAudit(currentScript, 2)"
        >
          拒绝审核
        </el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditVisible"
      :title="auditType === 1 ? '通过审核' : '拒绝审核'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="80px">
        <el-form-item label="剧本名称">
          <el-input v-model="auditForm.title" disabled />
        </el-form-item>
        <el-form-item label="审核备注" prop="remark">
          <el-input
            v-model="auditForm.remark"
            type="textarea"
            :rows="4"
            :placeholder="auditType === 1 ? '请输入审核通过的备注（可选）' : '请输入拒绝原因'"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="auditVisible = false">取消</el-button>
        <el-button
          :type="auditType === 1 ? 'success' : 'danger'"
          :loading="auditLoading"
          @click="handleSubmitAudit"
        >
          确认{{ auditType === 1 ? '通过' : '拒绝' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getScriptListAPI, updateScriptStatusAPI } from '@/api/script'
import { onMounted, ref, reactive } from 'vue'
import type { Script } from '@/types/script'
import type { FormInstance, FormRules } from 'element-plus'
import { RefreshRight, Picture } from '@element-plus/icons-vue'

const BASE_IMAGE_URL = import.meta.env.VITE_API_BASE_URL

// 响应式数据
const scriptList = ref<Script[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情对话框
const detailVisible = ref(false)
const currentScript = ref<Script | null>(null)

// 审核对话框
const auditVisible = ref(false)
const auditLoading = ref(false)
const auditType = ref<1 | 2>(1) // 1: 通过, 2: 拒绝
const auditFormRef = ref<FormInstance>()
const auditForm = reactive({
  id: 0,
  title: '',
  remark: ''
})

// 审核表单验证规则
const auditRules: FormRules = {
  remark: [
    {
      required: false,
      validator: (rule, value, callback) => {
        // 拒绝审核时必须填写备注
        if (auditType.value === 2 && !value) {
          callback(new Error('请输入拒绝原因'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 分类列表
const categories = [
  { id: 1, name: '剧情类' },
  { id: 2, name: '喜剧类' },
  { id: 3, name: '悬疑类' },
  { id: 4, name: '历史类' },
  { id: 5, name: '科幻类' }
]

// 获取剧本列表
const getScriptList = async () => {
  loading.value = true
  try {
    const res = await getScriptListAPI()
    if (res.data.code !== 1) {
      ElMessage.error(res.data.msg || '获取剧本列表失败')
      return
    }
    scriptList.value = res.data.data || []
    total.value = scriptList.value.length
  } catch (error) {
    ElMessage.error('网络请求失败')
    console.error('获取剧本列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 页码改变
const handlePageChange = (page: number) => {
  currentPage.value = page
  getScriptList()
}

// 每页数量改变
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  getScriptList()
}

// 查看详情
const handleViewDetail = (script: Script) => {
  currentScript.value = script
  detailVisible.value = true
}

// 打开审核对话框
const handleAudit = (script: Script, type: 1 | 2) => {
  if (script.status !== 0) {
    ElMessage.warning('该剧本已审核')
    return
  }

  auditType.value = type
  auditForm.id = script.id
  auditForm.title = script.title
  auditForm.remark = ''
  auditVisible.value = true
  detailVisible.value = false
}

// 提交审核
const handleSubmitAudit = async () => {
  if (!auditFormRef.value) return

  try {
    await auditFormRef.value.validate()

    auditLoading.value = true

    const res = await updateScriptStatusAPI(
      auditForm.id,
      auditType.value,
      auditForm.remark
    )

    if (res.data.code !== 1) {
      ElMessage.error(res.data.msg || '审核操作失败')
      return
    }

    ElMessage.success(auditType.value === 1 ? '审核通过' : '已拒绝该剧本')
    auditVisible.value = false

    // 刷新列表
    getScriptList()
  } catch (error) {
    console.error('审核失败:', error)
    if (error !== false) { // 排除表单验证失败
      ElMessage.error('审核操作失败')
    }
  } finally {
    auditLoading.value = false
  }
}

// 获取分类名称
const getCategoryName = (categoryId: number) => {
  const category = categories.find(cat => cat.id === categoryId)
  return category?.name || '未知分类'
}

// 获取状态类型
const getStatusType = (status: number) => {
  const statusMap: Record<number, '' | 'success' | 'warning' | 'danger' | 'info'> = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '待审核',
    1: '审核通过',
    2: '审核拒绝'
  }
  return statusMap[status] || '未知'
}

onMounted(() => {
  getScriptList()
})
</script>

<style scoped>
.script-audit-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 20px;
}

/* 图片错误状态 */
.image-error {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 24px;
}

.image-error-large {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 280px;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 48px;
}

/* 剧本详情样式 */
.script-detail {
  min-height: 400px;
}

.detail-content {
  padding: 10px 0;
}

.detail-header {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
  padding-bottom: 30px;
  border-bottom: 1px solid #ebeef5;
}

.detail-cover {
  width: 200px;
  flex-shrink: 0;
}

.detail-cover :deep(.el-image) {
  width: 100%;
  height: 280px;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.detail-basic-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 10px 0;
  line-height: 1.4;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  line-height: 1.6;
}

.info-label {
  color: #909399;
  min-width: 80px;
}

.info-value {
  color: #606266;
  flex: 1;
}

.price-item {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.price-value {
  font-size: 28px;
  font-weight: 600;
  color: #f56c6c;
}

.detail-description {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.description-text {
  font-size: 14px;
  color: #606266;
  line-height: 1.8;
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
}

/* 详情对话框响应式 */
@media (max-width: 768px) {
  .detail-header {
    flex-direction: column;
    align-items: center;
  }

  .detail-cover {
    width: 160px;
  }

  .detail-cover :deep(.el-image) {
    height: 224px;
  }

  .detail-title {
    font-size: 20px;
  }

  .price-value {
    font-size: 24px;
  }
}
</style>
